<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <!-- 消息提是区域 -->
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
      <!-- steps区域 -->
      <el-steps :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
      </el-steps>
      <!-- 表单区域 -->
      <el-form
        :model="addForm"
        :rules="addFormrules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <!-- tab导航区域 -->
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="tabBeforeLeave"
          @tab-click="tabClick"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateLisProps"
                @change="handleChange"
                clearable
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <!-- 渲染商品动态参数tab -->
            <el-form-item
              :label="item.attr_name"
              v-for="(item) in manyParamsData"
              :key="item.attr_id"
            >
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="val" v-for="(val, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <!-- 渲染商品静态属性tab -->
            <el-form-item
              v-for="(item) in onlyAttriData"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- upload图片操作 -->
            <el-upload
              :action="upPictureURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headersObj"
              :on-success="upPcSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" @click="addGoods()" class="btnAddClass">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog title="图片预览" :visible.sync="previewPcVisible" width="30%">
      <img :src="previewPcURL" alt>
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  created() {
    this.getCateList()
  },
  data() {
    return {
      /* 被激活的index值 */
      activeIndex: '0',
      /* 添加商品的表单数据 */
      addForm: {
        goods_name: '',
        /* 添加商品的分类 */
        goods_cat: [],
        goods_price: 0,
        goods_number: 0,
        goods_weight: 0,
        /* 添加商品的图片地址 */
        pics: [],
        /* 添加商品的详情描述 */
        goods_introduce: '',
        /* 商品参数数组 */
        attrs: []
      },
      /* 添加商品的表单数据的验证规则 */
      addFormrules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ]
      },
      /* 商品分类列表 */
      cateList: [],
      /* 商品分类级联选择器props属性对象 */
      cateLisProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true
      },
      /* 动态参数列表 */
      manyParamsData: [],
      onlyAttriData: [],
      /* 图片上传的url */
      upPictureURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      /* 设置图片上传的headers请求头对象 */
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      /* 控制预览图片对话框的显示隐藏 */
      previewPcVisible: false,
      /* 预览图片的url */
      previewPcURL: ''
    }
  },
  methods: {
    /* 获取商品分类列表 */
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        this.$message.error('获取商品分类列表失败')
        return
      }
      this.cateList = res.data
    },
    /* 监听商品分类级联选择器发生变化事件 */
    handleChange() {
      if (!this.cateId) {
        this.addForm.goods_cat = []
      }
    },
    /* tab跳转之前，促发的函数 */
    tabBeforeLeave(newactiveName, oldActiveName) {
      if (newactiveName !== '0') {
        if (!this.addForm.goods_cat.length) {
          this.$message.error('请先选择商品分类')
          return false
        }
        this.$refs.addFormRef.validate(valid => {
          console.log(valid)
          if (!valid) {
            console.log(111)
            return false
          }
        })
      }
    },
    /* 监听tab点击选中事件 */
    async tabClick(activeTab) {
      /* 选中的是，商品参数选项，发起请求，回去动态商品参数列表 */
      if (this.activeIndex === '1') {
        const { data: res1 } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'many' } }
        )
        if (res1.meta.status !== 200) {
          this.$message.error('获取动态参数信息失败')
          return
        }

        res1.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(' ')
        })
        this.manyParamsData = res1.data
      } else if (this.activeIndex === '2') {
        const { data: res2 } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: 'only' } }
        )
        if (res2.meta.status !== 200) {
          this.$message.error('获取静态属性信息失败')
          return
        }
        this.onlyAttriData = res2.data
      }
    },
    /* 处理图片预览效果 */
    handlePreview(file) {
      this.previewPcVisible = true
      this.previewPcURL = file.response.data.url
    },
    /* 处理图片移除操作 */
    handleRemove(file) {
      const path = file.response.data.tmp_path
      const delIndex = this.addForm.pics.findIndex(x => x.pics === path)
      this.addForm.pics.splice(delIndex, 1)
    },
    /* 图片上传成功操作 */
    upPcSuccess(respone) {
      this.addForm.pics.push({ pics: respone.data.tmp_path })
    },
    /* 发送请求，添加商品 */
    async addGoods() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整添加商品信息')
        }
      })
      /* 表单验证通过， 开始数据处理 */
      /* 进行深拷贝，防止出现数据不匹配问题 */
      var form = _.cloneDeep(this.addForm)
      /* 处理 goods_cat */
      form.goods_cat = form.goods_cat.join(',')
      /* 处理动态参数 */
      this.manyParamsData.forEach(item => {
        form.attrs.push({
          attr_id: item.attr_id,
          attr_vals: item.attr_vals.join(' ')
        })
      })
      /* 处理静态属性 */
      this.onlyAttriData.forEach(item => {
        form.attrs.push({
          attr_id: item.attr_id,
          attr_vals: item.attr_vals
        })
      })
      console.log(form)
      const { data: res } = await this.$http.post('goods', form)
      if (res.meta.status !== 201) {
        console.log(res)
        return this.$message.error('添加商品失败')
      }
      console.log(res)

      this.$message.success('添加商品成功')
      this.$router.push('/goods')
    }
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>

<style lang="scss" scoped>
.el-steps {
  margin: 20px 0;
}
.el-step__title {
  font-size: 12px;
}
.el-checkbox {
  margin: 0 6px 0 0 !important;
}
.el-dialog {
  img {
    width: 100%;
  }
}
.btnAddClass {
  margin-top: 20px;
}
</style>
